#pragma once
#include <iostream>
#include <pthread.h>

namespace MutexModule
{
    class Mutex
    {
    public:
        Mutex()
        {
            int n = pthread_mutex_init(&_mutex, nullptr);
            if (n != 0)
            {
                perror("init failed");
            }
        }

        void Lock()
        {
            int n = pthread_mutex_lock(&_mutex);
            if (n != 0)
            {
                perror("lock failed");
            }
        }

        void Unlock()
        {
            int n = pthread_mutex_unlock(&_mutex);
            if (n != 0)
            {
                perror("unlock failed");
            }
        }

        ~Mutex()
        {
            int n = pthread_mutex_destroy(&_mutex);
            if (n != 0)
            {
                perror("destroy failed");
            }
        }

    private:
        pthread_mutex_t _mutex;
    };

    // 采用RAII风格，进行管理
    class LockGuard
    {
    public:
        LockGuard(Mutex& mutex)
            :_mutex(mutex)
        {
            _mutex.Lock();
        }

        ~LockGuard()
        {
            _mutex.Unlock();
        }
    private:
        Mutex& _mutex;
    };
}